import axios from 'axios';
import 'dotenv/config';

type Msg = { role: 'system' | 'user' | 'assistant' | 'tool'; content: string };

export async function callDeepSeek(opts: {
    messages: Msg[];
    tools: Array<{
        name: string;
        description: string;
        parameters: any;
    }>;
}) {
    // 将我们的工具定义，包一层 { type: 'function', function: {...} }
    const toolSpecs = opts.tools.map(t => ({
        type: 'function',
        function: {
            name: t.name,
            description: t.description,
            parameters: t.parameters
        }
    }));

    const res = await axios.post(
        'https://api.deepseek.com/v1/chat/completions',
        {
            model: 'deepseek-chat',
            messages: opts.messages,
            tools: toolSpecs,
            tool_choice: 'auto' // 让模型在需要时自己调用
        },
        {
            headers: {
                Authorization: `Bearer ${process.env.DEEPSEEK_API_KEY}`,
                'Content-Type': 'application/json'
            },
            timeout: 30_000
        }
    );

    // 直接返回第一个 choice 的 message
    return res.data.choices[0].message as {
        role: 'assistant';
        content: string | null;
        tool_calls?: Array<{
            id: string;
            type: 'function';
            function: { name: string; arguments: string };
        }>;
    };
}
